<template>
  <div class="tag-panel">
    <!-- 分类筛选区：横向滚动 - 始终可见，不被遮罩覆盖 -->
    <div class="category-scroll">
      <!-- 一级分类 - 使用el-scrollbar实现滚动条隐藏效果 -->
      <el-scrollbar class="category-scrollbar" @wheel.prevent="onHandleScroll('group')">
        <div class="category-group">
          <span
            v-for="group in uniqueGroups"
            :key="group"
            @click="handleGroupClick(group)"
            :class="['group-tag', { active: selectedGroup === group }]"
          >
            {{ group }}
          </span>
        </div>
      </el-scrollbar>

      <!-- 二级分类 -->
      <el-scrollbar v-if="filteredSubcategories.length" class="category-scrollbar" @wheel.prevent="onHandleScroll('subgroup')">
        <div class="subcategory-group">
          <span
            v-for="item in filteredSubcategories"
            :key="item.name"
            @click="handleSubcategoryClick(item)"
            :class="['subgroup-tag', { active: selectedName === item.name }]"
          >
            {{ item.name }}
          </span>
          <!-- 清除二级分类选择按钮 -->
          <span
            v-if="selectedName"
            class="clear-subgroup"
            @click="clearSubcategorySelection"
          >
            <i class="el-icon-close"></i> 清除选择
          </span>
        </div>
      </el-scrollbar>
    </div>

    <!-- 标签列表区：流式布局 + 悬浮提示 - 这部分会被遮罩覆盖 -->
    <div class="tags-container">
      <!-- 加载/错误状态 - 只覆盖标签列表区域 -->
      <transition name="fade">
        <div v-if="showLoadingOverlay" class="loading-overlay">
          <div class="spinner"></div>
        </div>
      </transition>

      <transition name="fade">
        <div v-if="showError" class="error-text">{{ error }}</div>
      </transition>

      <div class="tags-wrapper" v-if="!showLoadingOverlay && !showError">
        <div class="tags-header">
          <h3>标签列表</h3>
                  <div class="pagination-bar">
          <button
            @click="changePage(1)"
            :disabled="pagination.page === 1"
            class="page-btn"
          >
            <i class="el-icon-d-arrow-left"></i>
          </button>
          <button
            @click="changePage(pagination.page - 1)"
            :disabled="pagination.page === 1"
            class="page-btn"
          >
            <i class="el-icon-arrow-left"></i>
          </button>
          <span class="page-info">
            第 {{ pagination.page }} / {{ pagination.totalPages }} 页
          </span>
          <button
            @click="changePage(pagination.page + 1)"
            :disabled="pagination.page === pagination.totalPages"
            class="page-btn"
          >
            <i class="el-icon-arrow-right"></i>
          </button>
          <button
            @click="changePage(pagination.totalPages)"
            :disabled="pagination.page === pagination.totalPages"
            class="page-btn"
          >
            <i class="el-icon-d-arrow-right"></i>
          </button>
        </div>
          <span class="tag-count">(共 {{ pagination.total }} 个)</span>
        </div>

        <div class="tags-grid">
          <el-tooltip
            v-for="tag in tags"
            :key="tag.id"
            :content="`${tag.label}\n${tag.value}`"
            placement="top"
            effect="light"
          >
            <div class="tag-card" @click="handleAddTagToPrompt(tag.value)">
              <div class="tag-label">{{ tag.label }}</div>
              <div class="tag-value">{{ tag.value }}</div>
            </div>
          </el-tooltip>
        </div>

        <!-- 空状态 -->
        <div v-if="tags.length === 0 && !loadingTags" class="empty-state">
          <i class="el-icon-search"></i>
          <p>未找到匹配标签</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, ref as vueRef } from 'vue';
import { ElScrollbar } from 'element-plus';
import { tagApi } from '@renderer/api/tags'; // 接口示例
import { useGenerationStore } from '@renderer/stores/useGenerationStore';


const generateStore = useGenerationStore();
// 状态管理
const categories = ref([]);
const tags = ref([]);
const pagination = ref({ total: 0, page: 1, pageSize: 50, totalPages: 0 });
const selectedGroup = ref('');
const selectedName = ref('');

// 滚动条引用
const groupScrollbarRef = vueRef();
const subgroupScrollbarRef = vueRef();

// 加载状态 - 优化：添加加载计时器，避免闪烁
const loading = ref(true);
const loadingTags = ref(false);
const error = ref('');
const loadingStartTime = ref(null);
const MIN_LOADING_DURATION = 250; // 最小加载时间(ms)，避免闪烁

// 计算属性：控制显示状态
const showLoadingOverlay = computed(() => {
  // 只有当实际加载状态为true时才显示
  return loading.value || loadingTags.value;
});

const showError = computed(() => {
  // 错误状态优先于加载状态
  return error.value && !loading.value && !loadingTags.value;
});

const handleAddTagToPrompt = (tag:string) =>{
  generateStore.params.prompt +=  "," + tag
}

// 初始化逻辑
onMounted(async () => {
  try {
    loadingStartTime.value = Date.now();
    const res = await tagApi().getCategories();
    categories.value = res.data.data || [];
    if (categories.value.length) {
      // 只默认选择一级分类，不选择二级分类
      selectedGroup.value = categories.value[0].group;
      await fetchTags();
    }
  } catch (err) {
    error.value = '分类加载失败';
    console.error(err);
  } finally {
    // 确保至少显示指定时间的加载状态
    const elapsed = Date.now() - (loadingStartTime.value || 0);
    if (elapsed < MIN_LOADING_DURATION) {
      await new Promise(resolve => setTimeout(resolve, MIN_LOADING_DURATION - elapsed));
    }
    loading.value = false;
  }
});

// 分类计算属性
const uniqueGroups = computed(() => [...new Set(categories.value.map(i => i.group))]);
const filteredSubcategories = computed(() =>
  categories.value.filter(i => i.group === selectedGroup.value)
);

// 标签获取逻辑 - 优化：添加最小加载时间
const fetchTags = async () => {
  try {
    loadingStartTime.value = Date.now();
    loadingTags.value = true;

    // 可以只传group参数，不传name参数
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      group: selectedGroup.value
    };

    // 只有当选择了二级分类时才添加name参数
    if (selectedName.value) {
      params.name = selectedName.value;
    }

    const res = await tagApi().getTags(params);
    tags.value = res.data.data || [];
    pagination.value = res.data.pagination || pagination.value;
  } catch (err) {
    error.value = '标签加载失败';
    console.error(err);
  } finally {
    // 确保至少显示指定时间的加载状态，避免闪烁
    const elapsed = Date.now() - (loadingStartTime.value || 0);
    if (elapsed < MIN_LOADING_DURATION) {
      await new Promise(resolve => setTimeout(resolve, MIN_LOADING_DURATION - elapsed));
    }
    loadingTags.value = false;
  }
};

// 处理滚动事件
const onHandleScroll = (type) => {
  const scrollbar = type === 'group' ? groupScrollbarRef.value : subgroupScrollbarRef.value;
  if (scrollbar) {
    scrollbar.$refs.wrapRef.scrollLeft += event.deltaY / 4;
  }
};

// 交互事件
const handleGroupClick = (group) => {
  if (selectedGroup.value === group) return;
  selectedGroup.value = group;
  // 选择新的一级分类时，清除二级分类选择
  selectedName.value = '';
  pagination.value.page = 1;
  fetchTags();
};

const handleSubcategoryClick = (item) => {
  if (selectedName.value === item.name) {
    // 再次点击已选中的二级分类，取消选择
    selectedName.value = '';
  } else {
    selectedName.value = item.name;
  }
  pagination.value.page = 1;
  fetchTags();
};

// 清除二级分类选择
const clearSubcategorySelection = () => {
  selectedName.value = '';
  pagination.value.page = 1;
  fetchTags();
};

const changePage = (page) => {
  if (page < 1 || page > pagination.value.totalPages) return;
  pagination.value.page = page;
  fetchTags();
};
</script>

<style scoped>
.tag-panel {
  position: relative;
  padding: 12px;
  min-height: 300px;
}

/* 分类滚动区 - 始终显示在遮罩上方 */
.category-scroll {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 16px;
  position: relative;
  z-index: 20; /* 确保分类区在遮罩上方 */
}

/* 标签列表容器 - 作为遮罩的定位参考 */
.tags-container {
  position: relative;
  min-height: 200px;
}

/* 优化：添加淡入淡出过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

/* 加载动画 - 只覆盖标签列表区域 */
.loading-overlay {
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 100%;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  transition: opacity 0.3s ease; /* 平滑过渡 */
}
.spinner {
  width: 40px; height: 40px;
  border: 4px solid var(--el-border-color);
  border-top: 4px solid var(--el-color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 滚动条样式 - 默认使用Element风格 */
.category-scrollbar {
  height: auto;
  &:deep(.el-scrollbar__wrap) {
    overflow-x: auto !important;
    overflow-y: hidden !important;
    height: auto !important;
    padding-bottom: 8px;
  }

  &:deep(.el-scrollbar__bar) {
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover:deep(.el-scrollbar__bar) {
    opacity: 1;
  }

  &:deep(.el-scrollbar__bar.is-horizontal) {
    height: 6px;
    left: 5px;
    right: 5px;
  }

  &:deep(.el-scrollbar__thumb) {
    background: var(--el-text-color-placeholder);
    border-radius: 3px;
    &:hover {
      background: var(--el-text-color-regular);
    }
  }

  &:deep(.el-scrollbar__track) {
    background: var(--el-border-color-lighter);
    border-radius: 3px;
  }
}

.category-group, .subcategory-group {
  display: flex;
  padding: 0 4px;
}

.group-tag, .subgroup-tag {
  padding: 6px 16px;
  margin-right: 10px;
  border-radius: 20px;
  font-size: 0.85rem;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s ease;
}

/* 主分类标签 - 默认使用Element主题色 */
.group-tag {
  background: var(--el-fill-color-light);
  font-weight: 500;
  &.active {
    background: var(--el-color-primary);
    color: var(--el-color-white);
    box-shadow: 0 2px 8px rgba(187, 134, 252, 0.3);
  }
  &:hover:not(.active) {
    background: var(--el-fill-color);
  }
}

/* 子分类标签 - 默认使用Element主题色 */
.subgroup-tag {
  background: var(--el-fill-color-blank);
  border: 1px solid var(--el-border-color);
  &.active {
    background: var(--el-color-success);
    color: var(--el-color-white);
    border-color: var(--el-color-success);
    box-shadow: 0 2px 8px rgba(37, 201, 123, 0.3);
  }
  &:hover:not(.active) {
    border-color: var(--el-border-color-light);
    background: var(--el-fill-color-light);
  }
}

/* 清除二级分类选择按钮 - 默认样式 */
.clear-subgroup {
  padding: 6px 12px;
  margin-right: 10px;
  border-radius: 20px;
  font-size: 0.8rem;
  cursor: pointer;
  white-space: nowrap;
  color: var(--el-text-color-placeholder);
  background: var(--el-fill-color-light);
  border: 1px solid var(--el-border-color-lighter);
  transition: all 0.2s;
  &:hover {
    color: var(--el-text-color-regular);
    background: var(--el-fill-color);
  }
}

/* 标签区 - 默认使用Element主题 */
.tags-wrapper {
  position: relative;
  min-height: 200px;
  transition: opacity 0.3s ease; /* 内容区域过渡 */
}
.tags-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.tag-count {
  font-size: 0.8rem;
  color: var(--el-text-color-placeholder);
}
.tags-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.tag-card {
  background: var(--el-color-white);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
  padding: 10px;
  min-width: 120px;
  max-width: 180px;
  transition: all 0.3s ease;
  &:hover {
    transform: translateY(-2px);
    box-shadow: var(--next-box-shadow-dark);
    border-color: var(--el-border-color);
  }
}
.tag-label {
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.tag-value {
  font-size: 0.75rem;
  color: var(--el-text-color-placeholder);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 空状态 - 默认样式 */
.empty-state {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: var(--el-text-color-placeholder);
  i { font-size: 2rem; margin-bottom: 8px; }
}

/* 分页栏：固定底部 - 默认使用Element主题 */
.pagination-bar {
  position: sticky;
  bottom: 12px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 16px;
  background: var(--el-color-white);
  padding: 10px;
  border-top: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 -2px 10px rgba(0,0,0,0.02);
}
.page-btn {
  padding: 4px 10px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  cursor: pointer;
  background: var(--el-color-white);
  transition: all 0.2s;
  &:hover:not(:disabled) {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}
.page-info {
  font-size: 0.8rem;
  color: var(--el-text-color-placeholder);
}

/* 错误提示 - 默认使用Element主题色 */
.error-text {
  text-align: center;
  color: var(--el-color-danger);
  padding: 16px;
  background: var(--el-color-danger-light-9);
  border-radius: 4px;
  border: 1px solid var(--el-color-danger-light-7);
  transition: opacity 0.3s ease; /* 错误信息过渡 */
  position: relative;
  z-index: 5;
}

</style>
